package com.example.hzit.filter;

import com.example.hzit.properties.SecurityGatewayProperties;
import com.example.hzit.util.JwtUtil;
import com.example.hzit.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.Ordered;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class HzitGlobalFilter extends AbstractGatewayFilterFactory<HzitGlobalFilter.Config> implements Ordered {

    @Autowired
    private SecurityGatewayProperties gatewayProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public HzitGlobalFilter() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            List<String> whites = gatewayProperties.getWhites();
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();
            String path = request.getURI().getPath();

            if (whites.contains(path)) {
                return chain.filter(exchange);
            }

            String authorization = request.getHeaders().getFirst("Authorization");
            if (authorization == null || !authorization.startsWith("Bearer ")) {
                return writeResponse(response, "无效的Authorization头！");
            }
            String token = authorization.substring(7);

            try {
                String uuid = JwtUtil.parseToken(token).get("user_key").toString();
                String key = "login_tokens:" + uuid;
                if (!redisTemplate.hasKey(key)) {
                    return writeResponse(response, "登录失败！");
                }
            } catch (Exception e) {
                return writeResponse(response, "解析token失败！");
            }

            return chain.filter(exchange);
        };
    }

    private Mono<Void> writeResponse(ServerHttpResponse response, String message) {
        return ResponseUtil.webFluxResponseWriter(response, message);
    }

    @Override
    public int getOrder() {
        return -100;
    }

    public static class Config {
        // 这里可以添加一些配置属性，如果需要的话
    }
}
